package me.magicall.db.sql.mysql;

import me.magicall.db.sql.As;
import me.magicall.db.sql.condition.OneCondition;
import me.magicall.db.sql.expression.ConstExpression;
import me.magicall.db.sql.from.TableWithAs;
import me.magicall.db.sql.select.DbOrder;
import me.magicall.db.sql.select.OneOrder;
import me.magicall.db.sql.select.ResultField;
import me.magicall.db.sql.select.Select;
import me.magicall.db.sql.select.Selectedable;
import me.magicall.db.sql.table.Column;
import me.magicall.db.sql.table.Table;

public class MysqlSelect extends Select {

	MysqlLimit limit;

	public MysqlSelect() {
		super();
	}

	public MysqlSelect(final Selectedable firstElement) {
		super(firstElement);
	}

	@Override
	protected String initPrefix() {
		return " SELECT ";
	}

	@Override
	public StringBuilder appendTo(final StringBuilder sb) {
		return limit == null ? super.appendTo(sb) : limit.appendTo(super.appendTo(sb).append(" "));
	}

	public MysqlLimit getLimit() {
		if (limit == null) {
			limit = new MysqlLimit();
		}
		return limit;
	}

	public void setLimit(final MysqlLimit limit) {
		this.limit = limit;
	}

	public void setOffset(final int offset) {
		getLimit().setOffset(offset);
	}

	public void setSize(final int size) {
		getLimit().setSize(size);
	}

	public static void main(final String[] args) {
		final MysqlSelect select = new MysqlSelect();
		select.addFrom(new Table("t1"));
		System.out.println("@@@@@@" + select);

		final Column id = new Column("id");
		final Column name = new Column();
		name.setName("name");
		final Column sexColumn = new Column("sex");
		final ResultField sex = new ResultField(sexColumn, new As("gender"));
		select.add(id, name, sex);
		System.out.println("@@@@@@" + select);

		select.addFrom(new TableWithAs(new Table("test"), new As("t2")));
		System.out.println("@@@@@@" + select);

		final OneCondition condition1 = OneCondition.equalsCondition(sexColumn, new ConstExpression("male"));
		final OneCondition condition2 = new OneCondition();
		condition2.setFirstArg(new ConstExpression(1));
		condition2.setSecondArg(id);
		select.addCondition(condition1, condition2);
		System.out.println("@@@@@@" + select);

		select.addGroupBy(id, name);
		System.out.println("@@@@@@" + select);

		select.addOrder(new OneOrder(id, DbOrder.DESC), new OneOrder(name));
		System.out.println("@@@@@@" + select);

		select.setOffset(01);
		select.setSize(10);
		System.out.println("@@@@@@" + select);
	}
}
